const SearchInfo = require("../models/SearchInfo");
const { Op } = require("sequelize");

//常用词库表
module.exports = class SearchManager {
  /**
   * 增加一个searchObj
   * @param {*} searchObj
   * @returns
   */
  static async addSearch(searchObj) {
    const result = await SearchInfo.create(searchObj);
    return result.toJSON();
  }

  /**
   * 批量新增Search
   * @param {*} obj
   * @returns
   */
  static async bulkCreateSearch(valueArr) {
    const _this = this;
    const deleteAll = await _this.deleteAll();
    const result = await SearchInfo.bulkCreate(valueArr);
    return result;
  }

  /**
   * 删除一个
   * @param {*} searchId
   */
  static async deleteSearch(searchId) {
    const result = await SearchInfo.destroy({
      where: {
        id: searchId,
      },
    });
  }

  /**
   * 删除所有
   * @param {*}
   */
  static async deleteAll() {
    const result = await SearchInfo.destroy({
      where: {},
    });
  }

  /**
   * 更新
   * @param {*} Id
   * @param {*} Obj
   */
  static async updateSearch(Id, Obj) {
    await SearchInfo.update(Obj, {
      where: {
        id: Id,
      },
    });
    const result = await SearchInfo.findOne({
      where: {
        id: Id,
      },
    });
    return result;
  }

  /**
   * 查询所有的search
   * @returns
   */
  static async getAllSearch() {
    const result = await SearchInfo.findAll();
    return JSON.parse(JSON.stringify(result));
  }

  /**
   * 查询所有的search 符号
   * @returns
   */
  static async getAllSearchSymbol() {
    const result = await SearchInfo.findAll({
      where: {
        type: "symbol",
      },
    });
    return JSON.parse(JSON.stringify(result));
  }
  /**
   * 拼音码搜索常用词库
   * @returns
   */
  static async searchByPinyinOrCh(search) {
    const result = await SearchInfo.findAll({
      raw: true,
      where: {
        [Op.or]: [
          { pinyin: { [Op.like]: `%${search}%` } },
          { detail: { [Op.like]: `%${search}%` } },
        ],
      },
    });
    return JSON.parse(JSON.stringify(result));
  }
};
